package com.dfbz.controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String uri=req.getRequestURI();
        String methodName = uri.substring(uri.lastIndexOf("/") + 1);
        Class<? extends BaseServlet> aClass = this.getClass();
        Method method=null ;
        try {
            method = aClass.getDeclaredMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            method.invoke(this,req,resp);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    protected HashMap<String,String> getParm(HttpServletRequest req){
        HashMap<String, String> hashMap = new HashMap<>();
        Map<String, String[]> map = req.getParameterMap();
        Set<Map.Entry<String, String[]>> entrySet = map.entrySet();
        for (Map.Entry<String, String[]> s:entrySet) {
            String key = s.getKey();
            String[] value = s.getValue();
            if (value.length>1){
                hashMap.put(key, Arrays.toString(value));
            }
            else {
                hashMap.put(key,value[0]);
            }
        }
        return hashMap;
    }
}
